<?php
declare (strict_types = 1);

namespace app\middleware;
use lizhili\Time;
use think\facade\Db;
class LizhiliApiInit
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //这里记录所有的访问数据
        list($start, $end) = Time::today();
        if($b=Db::name('statistics')->where('time','>=',$start)->where('time','<',$end)->find()){
            Db::name('statistics')->where('id',$b['id'])->inc('pv')->update();
            if(Db::name('statistics_show')->where('ip',$request->ip())->find()){
                if(!Db::name('statistics_show')->where('time','>=',$start)->where('time','<',$end)->where('ip',$request->ip())->find()){
                    Db::name('statistics')->where('id',$b['id'])->inc('uv')->update();
                }
            }else{
                Db::name('statistics')->where('id',$b['id'])->inc('ip')->update();
            }
        }else{
            $id=Db::name('statistics')->insertGetId([
                'time'=>time(),
                'ip'=>0,
                'pv'=>1,
                'uv'=>1
            ]);
            if(!Db::name('statistics_show')->where('ip',$request->ip())->find()){
                Db::name('statistics')->where('id',$id)->inc('ip')->update();
            }
        }
        $a=[
            'time'=>time(),
            'ip'=>$request->ip(),
            'url'=>$request->url(true),
            'data'=>json_encode(input('param.')),
            'method'=>$request->method(),
            'controller'=>$request->controller(),
            'module'=>'api',
            'action'=>$request->action(),
            'file'=>!$request->file() ? 0 : sizeof($request->file()),
        ];
        Db::name('statistics_show')->insert($a);


        return $next($request);
    }
}
